/** @format */
import {isDate, isPlainObject} from './utils';

function encode(url: string): string {
  return encodeURIComponent(url)
    .replace(/%40/g, '@')
    .replace(/%3A/gi, ':')
    .replace(/%24/g, '$')
    .replace(/%2C/gi, ',')
    .replace(/%20/g, '+')
    .replace(/%5B/gi, '[')
    .replace(/%5D/gi, ']');
}

export function buildURL(url: string, params?: any): string {
  if (!params) {
    return url;
  }
  const parts: Array<string> = []; // 用于存放所有编码后的参数['a=123','foo=baz']
  Object.keys(params).forEach(key => {
    const val = params[key];
    if (!val) {
      return; // 跳过这一次forEach
    }
    let values: string[];
    if (Array.isArray(val)) {
      values = val;
      key += '[]';
    } else {
      values = [val];
    }
    values.forEach(val => {
      if (isDate(val)) {
        val = val.toISOString();
      } else if (isPlainObject(val)) {
        val = JSON.stringify(val);
      }
      parts.push(`${encode(key)}=${encode(val)}`);
    });
  });
  const serializedParams = parts.join('&');
  if (serializedParams) {
    const hashMarkIndex = url.indexOf('#'); // 去掉url参数中的#部分
    if (hashMarkIndex > -1) {
      url = url.slice(0, hashMarkIndex);
    }
    url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
  }
  return url;
}
